﻿using System;
using System.Collections.Generic;
using System.Data.Services.Client;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace jp110311.StorageModels
{
    public class EntityServiceUtility
    {
        private readonly CloudStorageAccount _accont;
        private readonly CloudTableClient _tableClient;

        public EntityServiceUtility() : this( CloudStorageAccount.DevelopmentStorageAccount)
        {
        }

        public EntityServiceUtility(CloudStorageAccount account)
        {
            _accont = account;
            _tableClient = _accont.CreateCloudTableClient();
        }

        public TableServiceContext GetTableServiceContext()
        {
            var context = _tableClient.GetDataServiceContext();
            context.IgnoreResourceNotFoundException = true;
            context.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromMilliseconds(20));

            if (ContextCreated != null)
            {
                ContextCreated( this, new DataServiceContextCreatedEventArgs(context) );
            }
            return context;
        }

        public event EventHandler<DataServiceContextCreatedEventArgs> ContextCreated;
        public event EventHandler<EventArgs> BeforeSaveChange;

        public void DoSaveChange( TableServiceContext context )
        {
            if (BeforeSaveChange != null)
            {
                BeforeSaveChange(this, EventArgs.Empty);
            }
            if (SuppressBatch)
            {
                context.SaveChanges(SaveChangesOptions.None);
                return;
            }
            context.SaveChanges(SaveChangesOptions.Batch);
        }

        public bool SuppressBatch { get; set; }

        public CloudTableClient GetTableClient()
        {
            return _tableClient;
        }
    }
}
